package com.tree.redisson.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @ClassName com.tree.redisson
 * Description: <类功能描述>.
 * <br>
 * @Author frankzsliu
 * @Date 2020/11/8 2:01 下午
 * @Version 1.0
 */
@Slf4j
@Component
public class OrderService {
    private static int PRODUCT_NUM = 10;
    private static String LOCK_KEY = "order:decrease";
    public static String PRODUCT_ID = "1234-1234-1234";
    private static String REDIS_KEY = LOCK_KEY + ":" + PRODUCT_ID;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedisService redisService;

    public void init(Integer num) {
        Object obj = redisService.get(REDIS_KEY);
        System.out.println("初始化之前：" + obj);
        redisService.del(REDIS_KEY);
        redisService.set(REDIS_KEY, num);
        System.out.println("初始化之后：" + redisService.get(REDIS_KEY));
    }

    public String decreasePrice(Integer productQuantity) throws InterruptedException {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        // 加锁 操作很类似Java的ReentrantLock机制
        String result = "";
        try {
            result =  decrease();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return result;
    }

    public String decreasePriceWithLock(Integer productQuantity) throws InterruptedException {
        RLock lock = redissonClient.getLock(LOCK_KEY);
        // 加锁 操作很类似Java的ReentrantLock机制
        lock.lock();
        String result = "";
        try {
            result =  decrease();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            // 解锁
            lock.unlock();
        }
        return result;
    }

    private String decrease() {
        String result = "";
        int current = redisService.getInteger(REDIS_KEY);
        // 简单减价操作 没有重新写其他接口了
        if (current == 0) {
            result = "当前数量为0，不能在减了！！";
            log.error(Thread.currentThread() + ", result" + result);
            return result;
        } else {
            int decreasePrice = redisService.getInteger(REDIS_KEY) - 1;
            redisService.set(REDIS_KEY, decreasePrice);
            log.error(Thread.currentThread() + "，当前数量[" + current + "], 减价之后[" + decreasePrice + "]");
//            Random random = new Random();
//            int a  = random.nextInt(10);
//            Thread.sleep(a);
        }
        return result;


    }
}
